package com.creditease.tmsp.modules.sys.web;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.creditease.tmsp.common.config.Global;
import com.creditease.tmsp.common.persistence.IdGenerator;
import com.creditease.tmsp.common.web.BaseController;
import com.creditease.tmsp.modules.sys.entity.Invest;
import com.creditease.tmsp.modules.sys.service.InvestService;
import com.github.miemiedev.mybatis.paginator.domain.PageList;

/**
 * 
 * @Description: 
 * @Author: Wangty
 * @Company: 宜信-变现通项目组 
 * @Version: V1.0
 * @Create Date: 2014年9月28日
 */

@Controller
@RequestMapping(value = "index/invest")
public class InvestController extends BaseController {

    @Autowired
	private InvestService investService;
	
	@ModelAttribute
	public Invest get(@RequestParam(required = false) String id) {
		if (StringUtils.isNotBlank(id)) {
			return investService.getById(id);
		} else {
			return new Invest();
		}
	}
	
	
	@RequestMapping(value = {"list", ""})
	public String list(Invest invest, HttpServletRequest request,
	           HttpServletResponse response, Model model){
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.putAll(convertBeanToMap(invest));
		List<Invest> investList = investService.query(requestPageBounds(request), map);
		model.addAttribute("investList", (PageList<Invest>)investList);
		return "modules/index/investList";
		
	}
	
	
	@RequestMapping(value = "form")
	public String form(Invest invest, Model model) {
		
		model.addAttribute("invest", invest);
		return "modules/index/investForm";
	}
	
	
	@RequestMapping(value = "save")
	public String save(Invest invest, HttpServletRequest request,
			Model model, RedirectAttributes redirectAttributes) {
		
		if (!beanValidator(model, invest)) {
			return form(invest, model);
		}
		if (StringUtils.isNotBlank(invest.getId())) {
			investService.update(invest); 
		}else{
			invest.setId(IdGenerator.getId());    //规则UUID
			invest.setCreateTime(new Date());            //创建时间
			investService.save(invest);
		}
		addMessage(redirectAttributes, "恭喜您，购买成功！");
		return "redirect:" + Global.getAdminPath() + "/index/invest";
	}
	
	
	@RequestMapping(value = "delete")
	public String delete(String id, RedirectAttributes redirectAttributes) {
		investService.delete(id);
		addMessage(redirectAttributes, "操作成功");
		return "redirect:"+Global.getAdminPath()+"/index/invest";
	}
	
}
